from flask import request
from ..config.WXConfig import WxConfig
import urllib
import ssl
import json


def get_wx_user(code):
    return get_access_token(code)


def get_access_token(code):
    url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' + WxConfig.appID + '&secret=' + WxConfig.appsecret + '&code=' + code + '&grant_type=authorization_code'
    context = ssl._create_unverified_context()
    with urllib.request.urlopen(url, context=context) as f:
        resp_str = f.read().decode('utf-8')
        try:
            resp_json = json.loads(resp_str)
            if resp_json['access_token'] and resp_json['openid']:
                return get_user_info(resp_json['access_token'], resp_json['openid'])
            return None
        except Exception:
            return None


def get_user_info(access_token, open_id):
    url = 'https://api.weixin.qq.com/sns/userinfo?access_token='+ access_token +'&openid='+ open_id +'&lang=zh_CN'
    context = ssl._create_unverified_context()
    with urllib.request.urlopen(url, context=context) as f:
        resp_str = f.read().decode('utf-8')
        try:
            resp_json = json.loads(resp_str)
            return resp_json
        except Exception:
            return None
